import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  DatePicker,
  Select,
  Spin,
  message,
  Typography,
  Space,
  Button,
  Table,
  Tag
} from 'antd';
import {
  ShoppingCartOutlined,
  UserOutlined,
  DollarOutlined,
  EyeOutlined,
  ArrowUpOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { Line, Column, Pie } from '@ant-design/charts';
import dayjs from 'dayjs';
import { productAPI, orderAPI, userAPI, analyticsAPI } from '../../services/api';

const { Title } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

const BusinessDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(7, 'day'),
    dayjs()
  ]);
  const [refreshing, setRefreshing] = useState(false);
  
  // 统计数据
  const [stats, setStats] = useState({
    totalOrders: 0,
    totalRevenue: 0,
    totalUsers: 0,
    totalProducts: 0,
    todayOrders: 0,
    todayRevenue: 0
  });
  
  // 图表数据
  const [chartData, setChartData] = useState({
    orderTrend: [],
    revenueTrend: [],
    categoryStats: [],
    hotProducts: []
  });

  // 加载统计数据
  const loadStats = async () => {
    try {
      const [orderStats, productStats, userStats] = await Promise.all([
        orderAPI.getStats(),
        productAPI.getStats(),
        userAPI.getStats()
      ]);
      
      setStats({
        totalOrders: orderStats?.totalOrders || 0,
        totalRevenue: orderStats?.totalRevenue || 0,
        todayOrders: orderStats?.todayOrders || 0,
        todayRevenue: orderStats?.todayRevenue || 0,
        totalUsers: userStats?.totalUsers || 0,
        totalProducts: productStats?.totalProducts || 0
      });
    } catch (error) {
      console.error('加载统计数据失败:', error);
      message.error('加载统计数据失败');
    }
  };

  // 加载图表数据
  const loadChartData = async () => {
    try {
      const start = dateRange[0].startOf('day').toISOString();
      const end = dateRange[1].endOf('day').toISOString();
      const [hotProducts, orderTrend, revenueTrend, categoryStats] = await Promise.all([
        analyticsAPI.getHotProducts(10),
        analyticsAPI.getOrderTrend(start, end),
        analyticsAPI.getRevenueTrend(start, end),
        analyticsAPI.getCategoryStats()
      ]);
      
      setChartData({
        orderTrend: orderTrend.map(item => ({ date: item.date, value: item.value, type: '订单数' })),
        revenueTrend: revenueTrend.map(item => ({ date: item.date, value: item.value, type: '收入' })),
        categoryStats: categoryStats.map(item => ({ category: item.category, value: item.value })),
        hotProducts: Array.isArray(hotProducts) ? hotProducts : []
      });
    } catch (error) {
      console.error('加载图表数据失败:', error);
      message.error('加载图表数据失败');
    }
  };



  // 刷新数据
  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await Promise.all([loadStats(), loadChartData()]);
      message.success('数据刷新成功');
    } catch (error) {
      message.error('数据刷新失败');
    } finally {
      setRefreshing(false);
    }
  };

  // 日期范围变化
  const handleDateRangeChange = (dates) => {
    if (dates && dates.length === 2) {
      setDateRange(dates);
    }
  };

  // 初始加载
  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        await Promise.all([loadStats(), loadChartData()]);
      } finally {
        setLoading(false);
      }
    };
    
    loadData();
  }, []);

  // 当日期范围变化时重新加载图表数据
  useEffect(() => {
    if (!loading) {
      loadChartData();
    }
  }, [dateRange]);

  // 热门商品表格列
  const hotProductColumns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 60,
      render: (_, __, index) => (
        <Tag color={index < 3 ? 'gold' : 'default'}>
          {index + 1}
        </Tag>
      )
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => <Tag color="blue">{category}</Tag>
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
      sorter: (a, b) => (a.viewCount || 0) - (b.viewCount || 0)
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${parseFloat(price || 0).toFixed(2)}`,
      sorter: (a, b) => (a.price || 0) - (b.price || 0)
    }
  ];

  // 订单趋势图配置
  const orderTrendConfig = {
    data: chartData.orderTrend,
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#1890ff',
    point: {
      size: 3,
      shape: 'circle'
    },
    tooltip: {
      formatter: (datum) => {
        return {
          name: '订单数',
          value: `${datum.value} 单`
        };
      }
    }
  };

  // 收入趋势图配置
  const revenueTrendConfig = {
    data: chartData.revenueTrend,
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#52c41a',
    point: {
      size: 3,
      shape: 'circle'
    },
    tooltip: {
      formatter: (datum) => {
        return {
          name: '收入',
          value: `¥${datum.value}`
        };
      }
    }
  };

  // 分类统计图配置
  const categoryStatsConfig = {
    data: chartData.categoryStats,
    angleField: 'value',
    colorField: 'category',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}%'
    },
    interactions: [
      {
        type: 'element-active'
      }
    ]
  };

  return (
    <div className="business-dashboard">
      {/* 页面头部 */}
      <div className="page-header">
        <div className="header-content">
          <Title level={2}>业务数据看板</Title>
          <Space>
            <RangePicker
              value={dateRange}
              onChange={handleDateRangeChange}
              format="YYYY-MM-DD"
            />
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              loading={refreshing}
            >
              刷新
            </Button>
          </Space>
        </div>
      </div>

      <Spin spinning={loading}>
        {/* 统计卡片 */}
        <Row gutter={[16, 16]} className="stats-cards">
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总订单数"
                value={stats.totalOrders}
                prefix={<ShoppingCartOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总收入"
                value={stats.totalRevenue}
                prefix={<DollarOutlined />}
                precision={2}
                valueStyle={{ color: '#52c41a' }}
                suffix="元"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="用户总数"
                value={stats.totalUsers}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="商品总数"
                value={stats.totalProducts}
                prefix={<EyeOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 今日数据 */}
        <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
          <Col xs={24} sm={12}>
            <Card>
              <Statistic
                title="今日订单"
                value={stats.todayOrders}
                prefix={<ArrowUpOutlined />}
                valueStyle={{ color: '#1890ff' }}
                suffix="单"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12}>
            <Card>
              <Statistic
                title="今日收入"
                value={stats.todayRevenue}
                prefix={<DollarOutlined />}
                precision={2}
                valueStyle={{ color: '#52c41a' }}
                suffix="元"
              />
            </Card>
          </Col>
        </Row>

        {/* 趋势图表 */}
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col xs={24} lg={12}>
            <Card title="订单趋势" className="chart-card">
              <Line {...orderTrendConfig} height={300} />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="收入趋势" className="chart-card">
              <Line {...revenueTrendConfig} height={300} />
            </Card>
          </Col>
        </Row>

        {/* 分类统计和热门商品 */}
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col xs={24} lg={12}>
            <Card title="商品分类统计" className="chart-card">
              <Pie {...categoryStatsConfig} height={300} />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="热门商品排行" className="table-card">
              <Table
                columns={hotProductColumns}
                dataSource={chartData.hotProducts}
                pagination={false}
                size="small"
                scroll={{ y: 300 }}
                rowKey="id"
              />
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default BusinessDashboard;